#include <iostream>

#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

ns_control::Control *ctrl_ptr = nullptr;

// 通过ctrl + \的方式上线所有主机
void GoOnline(int signo)
{
    ctrl_ptr->GoOnline();
}

int main()
{
    signal(SIGQUIT, GoOnline);

    httplib::Server svr;
    ns_control::Control ctrl;
    ctrl_ptr = &ctrl;
    // 查看题目列表
    svr.Get("/all_questions", [&ctrl](const httplib::Request &res, httplib::Response &resp)
            {
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html; charset=utf-8"); });

    // 查看指定题目
    // 正则表达式匹配 d表示数字 ，+ 表示多个
    // one_question/123
    // R"()" c++11新特性，保持原生字符串的格式，自动转义
    svr.Get(R"(/one_question/(\d+))", [&ctrl](const httplib::Request &res, httplib::Response &resp)
            {
        std::string number = res.matches[1]; //获取题号
        std::string html;
        ctrl.OneQuestion(number, &html);
        resp.set_content(html ,"text/html; charset=utf-8"); });

    // 提交代码
    svr.Post(R"(/judge/(\d+))", [&ctrl](const httplib::Request &res, httplib::Response &resp)
             {
                 std::string number = res.matches[1]; // 获取题号
                 std::string out_val;
                 ctrl.Judge(number, res.body, &out_val);
                 resp.set_content(out_val, "application/json;charset=utf-8");
                 // resp.set_content("判断特定的题目 : " + number ,"text/plain; charset=utf-8");
             });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}